package com.zw.hrm.web.controller;

import com.zw.hrm.util.AjaxResult;
import com.zw.hrm.utils.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {
    //文件上传
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        //把文件上传到Fastdfs云服务器
        try {
            //原生的文件名：222.2.2.jpg :commons-io
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());

            String filePath = FastDfsApiOpr.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败");
        }
    }
    //文件上传
    @PostMapping("/uploadBytes")
    public AjaxResult uploadBytes(@RequestBody byte[]  file,@RequestParam("extName") String extName){
        //把文件上传到Fastdfs云服务器
        try {
            String filePath = FastDfsApiOpr.upload(file, extName);
            return AjaxResult.me().setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败");
        }
    }
    @DeleteMapping("/remove")
    public AjaxResult remove(String path){
        //把文件从fastdfs云服务器删除
        System.out.println(path);
        try {
            String[] split = path.split("/", 3);
            FastDfsApiOpr.delete(split[1],split[2]);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件删除失败");
        }
    }
    @GetMapping("/download")
    public byte[] download(@RequestParam("path") String path){
        try {
            //把文件从fastdfs云服务器删除
            String[] split = path.split("/", 3);
            byte[] bytes = FastDfsApiOpr.download(split[1], split[2]);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
